package logic

import (
	"context"
	"fmt"
	"goods/es"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchGoodListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSearchGoodListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchGoodListLogic {
	return &SearchGoodListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SearchGoodListLogic) SearchGoodList(in *goods.SearchGoodListRequest) (*goods.SearchGoodListResponse, error) {
	query := fmt.Sprintf(`{
							  "query": {
								"bool": {
								  "should": [
									{ "match": { "Name":  "%v" }},
									{ "match": { "Content": "%v"   }}
								  ]
								}
							  }
							}`, in.Search, in.Search)
	info, err := es.QueryData("good", query, int(in.Limit), int(in.Offset))
	if err != nil {
		return nil, err
	}

	goodsInfos := []*goods.Good{}
	for _, val := range info.Hits.Hits {
		goodsInfos = append(goodsInfos, &goods.Good{
			ID:      val.Source.ID,
			Name:    val.Source.Name,
			Content: val.Source.Content,
			Price:   val.Source.Price,
		})
	}

	return &goods.SearchGoodListResponse{
		Infos: goodsInfos,
	}, nil
}
